<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
       <el-form-item label="区域" prop="deptId">
        <select-input dsCode="sys_dept_community" v-model="queryParams.deptId" style="width:180px"/>
      </el-form-item>   
      <el-form-item label="房屋" prop="roomId">
        <el-input v-model="queryRoomName" placeholder="请选择" readonly @click="doSelectRoom('query')"/>
        <el-input v-model="queryParams.roomId" type="hidden"/>
      </el-form-item>
      <el-form-item label="车辆" prop="carPlate">
        <el-input
          v-model="queryParams.carPlate"
          placeholder="请输入车辆"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="退费项目" prop="feeType">
        <el-select v-model="queryParams.feeType" placeholder="请选择退费项目" clearable style="width:120px">
          <el-option
            v-for="dict in fee_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收费记录" prop="chargeNum">
        <el-input
          v-model="queryParams.chargeNum"
          placeholder="请输入收费记录"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="退费方式" prop="payWay">
        <el-select v-model="queryParams.payWay" placeholder="请选择" clearable style="width:120px">
            <el-option
              v-for="dict in pay_way"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="退费时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['service:chargeReturn:add']"
        >直接退费</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['service:chargeReturn:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chargeReturnList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="区域" align="center" prop="deptName" />
      <el-table-column label="收费单号" align="center" prop="chargeNum" />
      <el-table-column label="房屋" align="center" prop="roomId">
        <template #default="scope">
          {{scope.row.buildingName}} - {{scope.row.unitNum}} - {{scope.row.roomName}}
        </template>
      </el-table-column>
      <el-table-column label="车牌" align="center" prop="carPlate" />
      <el-table-column label="退费项目" align="center" prop="feeType">
        <template #default="scope">
          <dict-tag :options="fee_type" :value="scope.row.feeType"/>
        </template>
      </el-table-column>
      <el-table-column label="退费金额" align="center" prop="feeReturn" />
      <el-table-column label="退费方式" align="center" prop="payWay">
        <template #default="scope">
          <dict-tag :options="pay_way" :value="scope.row.payWay"/>
        </template>
      </el-table-column>
      <el-table-column label="退费时间" align="center" prop="createTime" width="180px"/>
      <el-table-column label="说明" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['service:chargeReturn:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['service:chargeReturn:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改退费记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="chargeReturnRef" :model="form" :rules="rules" label-width="80px">
        <template v-if="form.id">
        <el-form-item label="区域" prop="deptId">
          <el-input v-model="form.deptId" type="hidden" placeholder="请输入区域" />
          <el-input v-model="form.deptName" readonly placeholder="请输入区域" />
        </el-form-item>
        <el-form-item label="房屋" prop="roomId" v-if="form.roomId">
          <el-input v-model="form.roomId" type="hidden" placeholder="请输入房屋" />
          <el-input :value="form.buildingName + ' -' + form.unitNum + '-' + form.roomName" readonly placeholder="请输入房屋" />
        </el-form-item>
        <el-form-item label="车辆" prop="carId" v-if="form.carId">
          <el-input v-model="form.carId" type="hidden" placeholder="请输入车辆" />
          <el-input v-model="form.carPlate" readonly placeholder="请输入车辆" />
        </el-form-item>
        <el-form-item label="收费单号" prop="chargeId" v-if="form.chargeId">
          <el-input v-model="form.chargeId" type="hidden" placeholder="请输入收费记录" />
          <el-input v-model="form.chargeNum" readonly placeholder="请输入收费单号" />
        </el-form-item>
        </template>
        <template v-else>
        <el-form-item label="区域" prop="deptId">
          <select-input dsCode="sys_dept_community" v-model="form.deptId"/>
        </el-form-item>
        <el-form-item label="房屋" prop="roomId">
          <el-input v-model="formRoomName" placeholder="请选择" readonly @click="doSelectRoom('form')"/>
          <el-input v-model="form.roomId" type="hidden"/>
        </el-form-item>        
        <el-form-item label="车辆" prop="carId">        
          <el-select 
            v-model="form.carId" 
            placeholder="请输入车牌搜索"
            clearable filterable
            remote reserve-keyword
            :remote-method="loadCar"
            :loading="remoteLoading"
            @change="carChange">
            <el-option
              v-for="dict in carOptions"
              :key="dict.id"
              :label="dict.carPlate + '('+dict.personName+')'"
              :value="dict.id"
            />
          </el-select>
          <el-alert :title="'区域:'+carInfo.deptName+', 楼栋:'+ carInfo.buildingName + ', 业主:'+carInfo.personName" type="success" :closable="false" v-if="form.carId"/>
        </el-form-item> 
        </template>
        <el-form-item label="退费项目" prop="feeType" v-if="form.id">
          <dict-tag :options="fee_type" :value="form.feeType"/>
        </el-form-item>
        <el-form-item label="退费项目" prop="feeType" v-else>
          <el-select v-model="form.feeType" placeholder="请选择项目" clearable>
            <el-option  v-for="dict in fee_type" :key="dict.value"          
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="退费金额" prop="feeReturn">
          <el-input-number v-model="form.feeReturn" :readonly="form.id" placeholder="请输入退费金额" />
        </el-form-item>
        <el-form-item label="退费方式" prop="payWay">
          <el-select v-model="form.payWay" placeholder="请选择支付方式" >
            <el-option
              v-for="dict in pay_way"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <room-select :show="showRoomSelect" @select="selectRoom" :params="roomSelectParams"/>
  </div>
</template>

<script setup name="ChargeReturn">
import { listChargeReturn, getChargeReturn, delChargeReturn, addChargeReturn, updateChargeReturn } from "@/api/service/chargeReturn";
import { selectCar } from "@/api/archive/car";
import SelectInput from "@/components/FormInput/Select";
import RoomSelect from "@/components/Selection/Room";

const { proxy } = getCurrentInstance();
const { fee_type, pay_way } = proxy.useDict('fee_type', 'pay_way');

const chargeReturnList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);
const carOptions = ref([]);
const remoteLoading = ref(false);
const formRoomName = ref("");
const queryRoomName = ref("");
const showRoomSelect = ref(false);
const roomSelectParams = ref(null);
const roomInfo = ref(null);
const carInfo = ref(null);


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 't.id',
    isAsc: 'desc',
    deptId: null,
    roomId: null,
    carId: null,
    feeType: null,
    chargeNum: null,
    payWay: null,
    createTime: null,
  },
  rules: {
    deptId: [
      { required: true, message: "区域不能为空", trigger: "blur" }
    ],
    roomId: [
      { required: true, message: "房屋不能为空", trigger: "blur" }
    ],
    feeType: [
      { required: true, message: "退费项目不能为空", trigger: "change" }
    ],
    feeReturn: [
      { required: true, message: "退费金额不能为空", trigger: "blur" }
    ],
    payWay: [
      { required: true, message: "退费方式不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询退费记录列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && '' != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  listChargeReturn(queryParams.value).then(response => {
    chargeReturnList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function doSelectRoom(params){
  roomSelectParams.value = params;
  showRoomSelect.value = true;
}
function selectRoom(room){
  showRoomSelect.value = false;
  if(room == null){
    form.value.roomId = null;
    formRoomName.value = null;
    queryParams.value.roomId = null;
    queryRoomName.value = null;
    return;
  }
  if(room.params == 'form'){
    form.value.roomId = room.id;
    formRoomName.value = room.name;
  }else{
    queryParams.value.roomId = room.id;
    queryRoomName.value = room.name;
  }
}

/** 选择车辆 */
function carChange(){ 
  for(let i=0;i<carOptions.value.length;i++){
    if(carOptions.value[i].id == form.value.carId){
      carInfo.value = carOptions.value[i];
      form.value.deptId = carInfo.value.deptId;
      break;
    }
  }
}

function loadCar(label) {
  remoteLoading.value = true;
  if(!label){
    carOptions.value = [];
    remoteLoading.value = false;
    return;
  }
  selectCar({pageSize:10,pageNum: 1,carPlate: label}).then(resp => {
    carOptions.value = resp.rows;
    remoteLoading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    roomId: null,
    carId: null,
    carPlate: null,
    feeType: null,
    chargeId: null,
    feeReturn: null,
    payWay: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("chargeReturnRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "直接退费";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getChargeReturn(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改退费记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["chargeReturnRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateChargeReturn(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addChargeReturn(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除选中的退费记录数据项？').then(function() {
    return delChargeReturn(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service/chargeReturn/export', {
    ...queryParams.value
  }, `chargeReturn_${new Date().getTime()}.xlsx`)
}


getList();
</script>
